﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponents.Ini;
using ProgNetComponents.Data.SqlCe;
using ProgNetComponentsDx.Layout;
using ProgNetComponentsDx.Options;
using ProgNetComponents.Classes;
using ProgNetComponentsDx.Browsers;
using System.Diagnostics;

namespace BuildHelper.Init
{
    public partial class InitForm : ProgNetComponentsDx.Forms.BaseInitForm
    {
        public InitForm()
        {
            InitializeComponent();
            this.lblTitle.Text = Application.ProductVersion;
            this.Text = Application.ProductName;
        }
        
        ProgNetComponents.Data.SqlCe.SqlCeDataManager helper = new ProgNetComponents.Data.SqlCe.SqlCeDataManager();
        
        protected override void PreInit()
        {
            base.PreInit();
            BrowserCache.SaveLayouts = true;
            BrowserCache.BeforeBrowserShowDialog += new BrowserHandler(BrowserCache_BeforeBrowserShowDialog);
            GlobalTools.FilesTools.InitLogsDir();

            SetProgressText("Inicjalizacja bazy danych.");
            IniFile iniFile = new IniFile(Application.StartupPath + "\\BuildHelper.ini");
            iniFile.ReadIni();
            string dbFile = iniFile.GetValueFormCache("Main", "DB");
            if (dbFile.IsNullOrEmpty())
                dbFile = Application.StartupPath + "\\BuildHelper.sdf";
            
            ProgNetComponents.Data.SqlCe.SqlCeDataManager.GlobalConnectionString = "Data Source=" + dbFile + "; Encrypt Database=False; Max Database Size = 4091; Default Lock Timeout = 10000"; //File Mode=Read Write;
            //try
            //{
            //    HibernateTools.ConfigureHibernate();
            //}
            //catch { }
            int lastAction = 0;
            if (System.IO.File.Exists(dbFile))
            {
                try
                {
                    object obj = helper.ExecuteScalar("SELECT STP_OP_WARTOSC FROM STP_OPCJE WHERE STP_OP_NAZWA = 'DB_UPDATE'");
                    if (obj != null)
                    {
                        lastAction = obj.AsInt();
                    }
                }
                catch { }
            }
            AppUpdate.Update(lastAction);
        }

        void BrowserCache_BeforeBrowserShowDialog(BrowserEventArgs e)
        {
            if (Init.InitFormBrowserNames.Setup.Srodowiska.IsTheSameKey(e.BrowserId))
            {
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.Srodowiska.UpdateOnOpen))
                {
                    if (OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.Srodowiska.EnvSource) != BuildHelper.Setup.Srodowiska.EnvSource.SoftUpdate)
                    {
                        Setup.Srodowiska.Tools.UpdateAllEnvs(false, null, false);
                    }
                }
            }
        }

        protected override ProgNetComponentsDx.Data.SelectDataManagerCreator CreateDataManagerCreator()
        {
            return new ProgNetComponentsDx.Data.SqlCeSelectDataManagerCreator();
        }
        protected override ProgNetComponents.Data.DataManager CreateDataManagerForBrowsers()
        {
            SqlCeDataManager g = new SqlCeDataManager();
            g.AutoLogExceptions = true;
            return g;
        }
        protected override LayoutGrabber CreateLayoutGrabber()
        {
            SqlCeLayoutGrabber g = new SqlCeLayoutGrabber();
            g.Manager.AutoLogExceptions = true;
            g.TableName = "STP_LAYOUT";
            g.XmlColumn = "STP_LAYOUT_XML_IMG";
            g.LayoutNameColumn = "STP_LAYOUT_NAZWA";
            g.ControlNameColumn = "STP_LAYOUT_KONTROLKA";
            return g;
        }
        protected override OptionGrabber CreateOptionGrabber()
        {
            SqlCeOptionGrabber g = new SqlCeOptionGrabber();
            g.TableName = "STP_OPCJE";
            g.OptionNameColumn = "STP_OP_NAZWA";
            g.OptionValueColumn = "STP_OP_WARTOSC";
            return g;
        }
        protected override ProgNetComponentsDx.Shortcut.ShortcutGrabber CreateShotrcutsGrabber()
        {
            ProgNetComponentsDx.Shortcut.SqlCeShortcutGrabber g = new ProgNetComponentsDx.Shortcut.SqlCeShortcutGrabber();
            g.ShortcutNameColumn = "STP_SC_NAZWA";
            g.ShortcutValueColumn = "STP_SC_WARTOSC";
            g.TableName = "STP_SHORTCUT";
            return g;
        }
        protected override void InitOptions()
        {
            base.InitOptions();
            OptionCache.GetOption(InitFormOptionNames.Rozne.Skorka).DefaultValue = this.LookAndFeel.ActiveSkinName;
            OptionCache.GetOption(InitFormOptionNames.Rozne.Styl).DefaultValue = this.LookAndFeel.Style;
            CreateDefFiles();
        }
        protected override void InitBrowsers()
        {
            base.InitBrowsers();
            Setup.ProcedurySql.CustomBrowsers.BrowserTools.RegisterCustomBrowsers();
        }
        private void CreateDefFiles()
        {
            string str ="";
            int i = helper.ExecuteScalar("SELECT STP_OP_WARTOSC FROM STP_OPCJE WHERE STP_OP_NAZWA = 'APP_UPDATE'").AsInt();
            if (i < 1 )
            {
                str = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseProc);
                if (str.IsNullOrEmpty())
                {
                    str = GlobalTools.TortoiseTools.GetDefaultTortoiseProcPath();
                    OptionCache.SetOptionValue(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseProc, str, true);
                }
                str = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn);
                if (str.IsNullOrEmpty())
                {
                    str = GlobalTools.TortoiseTools.GetDefaultTortoiseSvnPath();
                    OptionCache.SetOptionValue(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn, str, true);
                }
                str = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.BazyDanych.PlSqlDeveloper);
                if (str.IsNullOrEmpty())
                {
                    str = GlobalTools.DBTools.GetPlSqlDeveloperPath();
                    OptionCache.SetOptionValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.BazyDanych.PlSqlDeveloper, str, true);
                }
                str = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.OperacjeNaPlikach.WinMerge);
                if (str.IsNullOrEmpty())
                {
                    str = GlobalTools.FilesTools.GetDefaultWinMergePath();
                    OptionCache.SetOptionValue(Init.InitFormOptionNames.Work_Group.OperacjeNaPlikach.WinMerge, str, true);
                }
                str = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.BazyDanych.SqlTools);
                if (str.IsNullOrEmpty())
                {
                    str = GlobalTools.DBTools.GetSqlToolsPath();
                    OptionCache.SetOptionValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.BazyDanych.SqlTools, str, true);
                }
                
                object ob = helper.ExecuteNonQuery("INSERT INTO STP_OPCJE(STP_OP_NAZWA, STP_OP_WARTOSC) VALUES (@p1, @p2)", new NamedObject("@p1", "APP_UPDATE"), new NamedObject("@p2", "1"));
            }
            if (!OptionCache.SavedOptions.Contains(OptionCache.GetKey(Init.InitFormOptionNames.Narzedzia_Group.TelnetConsole.TelnetProgram)))
            {
                str = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Narzedzia_Group.TelnetConsole.TelnetProgram);
                if (str.IsNullOrEmpty())
                {
                    str = Application.StartupPath.TrimEnd('\\') + "\\apps\\putty.exe";
                    OptionCache.SetOptionValue(Init.InitFormOptionNames.Narzedzia_Group.TelnetConsole.TelnetProgram, str, true);
                }
            }
        }

        protected override void InitLangouage()
        {
            base.InitLangouage();
            //ProgNetComponentsDx.Language.ProgNetLanguage.SetPLLocalizer();
            ProgNetComponentsDx.Language.ProgNetLanguage pl = new ProgNetComponentsDx.Language.ProgNetLanguage(new System.Globalization.CultureInfo("pl-PL"));
            pl.RegisterManager("DB", LNG.DB.ResourceManager);
            ProgNetComponentsDx.Language.ProgNetLanguage.LogMissingValues = true;
            ProgNetComponentsDx.Language.ProgNetLanguage.CurrentLanguageCode = "pl-PL";
        }

        protected override DataTable BrowserCache_GetStaticData(object browserId)
        {
            DataTable dt = null;
            if (BrowserCache.IsTheSameBrowser(browserId, InitFormBrowserNames.Statyczne.TypySerwerow))
            {
                dt = GetStaticTable(InitFormBrowserNames.Statyczne.TypySerwerow);
                dt.Rows.Add(GlobalTools.ServerTools.ServerType.JBoss4, "JBoss 4");
                dt.Rows.Add(GlobalTools.ServerTools.ServerType.JBoss5, "JBoss 5");
                dt.Rows.Add(GlobalTools.ServerTools.ServerType.OAS, "Oracle Application Server");
                dt.Rows.Add(GlobalTools.ServerTools.ServerType.WebLogic, "WebLogic");
            }
            else if (BrowserCache.IsTheSameBrowser(browserId, InitFormBrowserNames.Statyczne.FreeDrives))
            {
                dt = new DataTable(InitFormBrowserNames.Statyczne.FreeDrives.ToString());
                dt.Columns.Add("DRIVE");
                System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
                List<int> extDrives = new List<int>();
                foreach (System.IO.DriveInfo d in drives)
                    extDrives.AddIfNotExist((int)(d.RootDirectory.Name[0]));
                for (int i = (int)('A'); i <= (int)('Z'); i++)
                {
                    if (!extDrives.Contains(i))
                        dt.Rows.Add((char)i + "");
                }
            }
            else if (BrowserCache.IsTheSameBrowser(browserId, InitFormBrowserNames.Statyczne.BranczeSVN))
            {
                dt = GetBranczeSVN();
            }
            else if (BrowserCache.IsTheSameBrowser(browserId, InitFormBrowserNames.Statyczne.SubstedDrives))
            {
                dt = GetSubstedDrives();
            }
            return dt;
        }

        #region subst drives
        private DataTable substTable;
        Process cmdGetSubstedDrives = null;
        private DataTable GetSubstedDrives()
        {
            DataTable dt = new DataTable(InitFormBrowserNames.Statyczne.SubstedDrives.ToString());
            dt.Columns.Add("DRIVE");
            dt.Columns.Add("KATALOG");
            substTable = dt;
            cmdGetSubstedDrives = GlobalTools.CreateCMDProcess(Get_SubstedDrives);
            cmdGetSubstedDrives.EchoOff();
            cmdGetSubstedDrives.Execute("subst");
            cmdGetSubstedDrives.Echo("exit");
            while (cmdGetSubstedDrives != null && !Program.IsExit)
            {
                Application.DoEvents();
            }
            return dt;
        }
        public void Get_SubstedDrives(object sender, DataReceivedEventArgs e)
        {
            if (e.Data.IsNotNull())
            {
                string str = e.Data.AsString();
                string substMask = "^([a-zA-Z]):\\\\:\\s*=>\\s*(.*)$";
                if (str.XMatch(substMask))
                {
                    substTable.Rows.Add(str.GetFirstMatch(substMask, 1), str.GetFirstMatch(substMask, 2));
                }
            }
            if (e.Data.AsString() == "exit")
            {
                try
                {
                    cmdGetSubstedDrives.KillProcessTree();
                    cmdGetSubstedDrives.Dispose();
                }
                catch { }
                cmdGetSubstedDrives = null;
            }
        }
        #endregion

        #region SVN Brancze
        class SvnBranches
        {
            private static SvnBranches _Instance;
            public static SvnBranches Instance
            {
                get
                {
                    if (_Instance == null)
                        _Instance = new SvnBranches();
                    return _Instance;
                }
            }
            private DataTable tmpTable = null;
            private bool getData = false;
            private string url = "";
            private string katalog = "";
            bool isReading = false;
            Process cmd = null;

            private void Get_BranczeSVN(object sender, DataReceivedEventArgs e)
            {
                if (e.Data.IsNotNull())
                {
                    if (e.Data.AsString() == "END READ")
                    {
                        isReading = false;
                        return;
                    }
                    if (e.Data.AsString() == "STOP GET DATA")
                    {
                        getData = false;
                        cmd.CallExit();
                        try
                        {
                            cmd.WaitForExit();
                            cmd.KillProcessTree();
                            cmd.Dispose();
                            cmd = null;
                        }
                        catch { }
                    }
                    if (getData && e.Data.AsString().EndsWith("/"))
                    {
                        string brancz = e.Data.AsString().Replace("/", "");
                        string name = brancz;
                        if (tmpTable.RowExists("NAZWA = " + name.EscapeSql()))
                        {
                            name = katalog + "-" + name;
                        }
                        tmpTable.Rows.Add(name, url + "/" + katalog + "/" + brancz);
                    }
                    if (e.Data.AsString() == "GET DATA")
                    {
                        getData = true;
                    }
                }
            }

            public DataTable GetData()
            {
                DataTable dt = new DataTable(InitFormBrowserNames.Statyczne.BranczeSVN.ToString());
                dt.Columns.Add("NAZWA");
                dt.Columns.Add("URL");
                tmpTable = dt;
                url = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.URL.Svn).TrimEnd('/');
                dt.Rows.Add("trunk", url + "/trunk");
                if (GlobalTools.TortoiseTools.CanUseTortoiseSvn())
                {
                    cmd = GlobalTools.CreateCMDProcess(Get_BranczeSVN);
                    getData = false;
                    isReading = false;
                    cmd.EchoOff();
                    cmd.Execute("echo GET DATA");
                    GlobalTools.TortoiseTools.AddSvnToPath(cmd);
                    string[] katalogi = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.URL.KatalogiSvn).Split(',');
                    foreach (string k in katalogi)
                    {
                        isReading = true;
                        katalog = k;
                        cmd.Execute("svn list " + url + "/" + k.Trim());
                        cmd.Echo("END READ");
                        while (isReading)
                        {
                            System.Threading.Thread.Sleep(50);
                        }
                    }
                    cmd.Execute("echo STOP GET DATA");
                }
                return dt;
            }
        }
        private DataTable GetBranczeSVN()
        {
            return SvnBranches.Instance.GetData();
        }

        
        #endregion

        private DataTable GetStaticTable(object id)
        {
            DataTable dt = new DataTable(id.ToString());
            dt.Columns.Add("KOD");
            dt.Columns.Add("NAZWA");
            return dt;
        }
    }
}

